<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form inline>
        <el-form-item label="">
          <el-select
            v-model="listQuery.category_id"
            size="small"
            default-first-option
            style="width: 180px"
            placeholder="能源类型"
            clearable
            @change="change"
          >
            <el-option
              v-for="(item, index) in joinArr"
              :key="index"
              :label="item.name"
              :value="item.category_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-select
            v-model="listQuery.category_id"
            size="small"
            default-first-option
            style="width: 180px"
            placeholder="报表类型"
            clearable
            @change="change"
          >
            <el-option
              v-for="(item, index) in joinArr1"
              :key="index"
              :label="item.name"
              :value="item.category_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="value1"
            size="small"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="listQuery.title"
            size="small"
            style="width: 200px"
            class="filter-item"
            placeholder="能源维度"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >
            查询
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px"
            type="primary"
            icon="el-icon-download"
          >
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        key="tableKey"
        :data="list"
        v-loading="listLoading"
        element-loading-text="加载中"
        border
        fit
        stripe
        highlight-current-row
        style="width: 100%"
        :header-cell-style="{
          background: '#E3ECFB',
          color: '#303133',
          fontWeight: '500'
        }"
      >
        <el-table-column align="center" label="编号" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="能源类型">
          <template slot-scope="scope">
            <span>电</span>
            <!-- <span>{{ scope.row.station_name }}</span> -->
          </template>
        </el-table-column>
        <el-table-column align="center" label="报表类型">
          <template slot-scope="scope">
            <span>明细报表</span>
            <!-- <span>{{ scope.row.station_code }}</span> -->
          </template>
        </el-table-column>
        <el-table-column align="center" label="所属类型">
          <template slot-scope="scope">
            <span>/</span>
            <!-- <span>{{ scope.row.name }}</span> -->
          </template>
        </el-table-column>
        <el-table-column align="center" label="能源维度">
          <template slot-scope="scope">
            <span>日</span>
            <!-- <span>{{ scope.row.name }}</span> -->
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="图片" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-image
              style="width: 60px;"
              :src="scope.row.image_path"
              :preview-src-list="[scope.row.image_path]"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column> -->

        <el-table-column align="center" label="时间" sortable prop="created_at">
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" label="状态" width="79px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status==1 ? 'success' : 'warning'">
              <span>{{ scope.row.status == 1?'已显示':'已停用' }}</span>
            </el-tag>
          </template>
        </el-table-column> -->

        <el-table-column
          align="center"
          label="更新时间"
          sortable
          prop="updated_at"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.updated_at }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          sortable
          prop="sort"
          label="排序"
          class-name="overflow-on"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.sort }}
            <el-input
              size="small"
              v-if="scope.row.show == 1"
              max="50"
              v-model="scope.row.sort"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="320">
          <template slot-scope="scope">
            <el-button
              plain
              v-if="scope.row.show == 1"
              size="small"
              @click="orderHandleDo(scope.row)"
              >保存</el-button
            >
            <el-button plain v-else size="small" @click="orderHandle(scope.row)"
              >排序</el-button
            >
            <!-- <el-button plain size="small" type="primary" @click="handleEdit(scope.row, 'edit')">编辑</el-button> -->
            <el-button
              plain
              size="small"
              type="primary"
              @click="updateAction(scope.row, 'edit')"
              >编辑</el-button
            >

            <!-- <el-button plain v-if="scope.row.status == 1" size="small" type="warning" @click="changeStatus(scope.row, 0)">去停用</el-button> -->
            <!-- <el-button plain v-else size="small" type="success" @click="changeStatus(scope.row, 1)">去发布</el-button> -->
            <el-button
              plain
              size="small"
              type="danger"
              @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container text-right">
        <el-pagination
          background
          :total="pagination.total"
          :current-page="listQuery.page"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        class="small-space"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="站点类型" required>
          <el-select
            size="small"
            v-model="temp.category_id"
            default-first-option
            style="width: 180px"
            placeholder="所属位置"
            clearable
          >
            <el-option
              v-for="(item, index) in categoryArr"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="站点名称" required>
          <el-input
            size="small"
            v-model="temp.station_name"
            width="100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="站点编号" required>
          <el-input
            size="small"
            v-model="temp.station_code"
            width="100px"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" required>
          <el-upload
            class="avatar-uploader"
            :action="uploadPath"
            :headers="header"
            :show-file-list="false"
            :on-success="handleImageSuccess"
          >
            <img
              v-if="temp.image_path"
              :src="temp.image_path"
              style="width: 200px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-tag type="warning">
            温馨提示：图片尽量压缩后上传，尽量不超过1M</el-tag
          >
        </el-form-item>
        <el-form-item label="定位">
          <el-input
            class="widthpick"
            size="small"
            v-model="temp.station_mapx"
            placeholder="请输入纬度"
          ></el-input>
          (纬度)
          <el-input
            class="widthpick"
            size="small"
            v-model="temp.station_mapy"
            placeholder="请输入经度"
          ></el-input>
          (经度)
          <template>
            <div>
              <baidu-map
                style="display:flex;flex-direction: column-reverse;"
                id="allmap"
                ref="map"
                @ready="mapReady"
                :center="center"
                @click="getLocation"
                :scroll-wheel-zoom="true"
              >
                <div style=" margin-bottom:10px">
                  <bm-auto-complete
                    v-model="searchJingwei"
                    :sugStyle="{ zIndex: 999999 }"
                  >
                    <el-input
                      size="small"
                      v-model="searchJingwei"
                      style="width:300px;margin-right:15px"
                      placeholder="输入地址"
                    ></el-input>
                  </bm-auto-complete>
                  <el-button
                    size="small"
                    type="primary"
                    @click="getBaiduMapPoint"
                    >搜索</el-button
                  >
                </div>
                <bm-map-type
                  :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"
                  anchor="BMAP_ANCHOR_TOP_LEFT"
                ></bm-map-type>
                <bm-marker
                  v-if="infoWindowShow"
                  :position="{ lng: info.longitude, lat: info.latitude }"
                >
                  <bm-label
                    content=""
                    :labelStyle="{ color: 'red', fontSize: '24px' }"
                    :offset="{ width: -8, height: 100 }"
                  />
                </bm-marker>
                <bm-info-window
                  :position="{ lng: info.longitude, lat: info.latitude }"
                  :show="infoWindowShow"
                  @clickclose="infoWindowClose"
                >
                  <p style="margin:2px;">纬度:{{ info.latitude }}</p>
                  <p style="margin:2px;">
                    经度:{{ info.longitude }}
                    <el-button
                      size="small"
                      plain
                      type="primary"
                      @click="getBaiduMapPointToInput"
                      style="float:right;"
                      >选定</el-button
                    >
                  </p>
                </bm-info-window>
              </baidu-map>
            </div>
          </template>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number size="small" v-model="temp.sort" />
          <el-tag type="warning">
            备注：前台页面显示顺序由小到大正序排列显示</el-tag
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="create"
          >确 定</el-button
        >
        <el-button v-else type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  List,
  Info,
  Save,
  Del,
  Status,
  Sort,
  Ct_List,
  Ct_AllList,
  Ct_Save,
  Ct_Del,
  Ct_Status,
  Ct_Sort
} from "@/api/station";
import { getToken } from "@/utils/auth";
import { uploadPath } from "@/utils/common";
import Vue from "vue";
import BaiduMap from "vue-baidu-map";

// 设置百度地图API的ak值
Vue.use(BaiduMap, {
  ak: "gBsCY3a0S5Pej0dommGEMi5pRAjIYciA"
});
export default {
  data() {
    return {
      //百度地图
      infoWindowShow: false,
      longitude: "",
      latitude: "",
      searchJingwei: "",
      info: {
        longitude: "",
        latitude: ""
      },
      joinArr: [{ name: "水" }, { name: "电" }, { name: "气" }, { name: "热" }],
      joinArr1: [
        { name: "水报表" },
        { name: "电报表" },
        { name: "气报表" },
        { name: "热报表" }
      ],
      center: { lng: 0, lat: 0 },
      point: "",
      //百度地图end
      list: null,
      categoryArr: null,
      changeIndex: -1,
      pagination: {},
      dialogFormVisible: false,
      temp: {
        title: "",
        link_url: "",
        image_path: "",
        sort: 0
      },
      listQuery: {
        page: 1,
        limit: 10,
        title: "",
        category_id: null
      },
      uploadPath: uploadPath,
      dialogStatus: null,
      dialogTitle: "",
      header: {
        Authorization: getToken()
      }
    };
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  created() {
    this.getList(), this.getCtList();
  },

  methods: {
    //地图初始化
    mapReady({ BMap, map }) {
      // 选择一个经纬度作为中心点
      this.point = new BMap.Point(113.27, 23.13);
      map.centerAndZoom(this.point, 12);
      this.BMap = BMap;
      this.map = map;
    },
    //点击获取经纬度
    getLocation(e) {
      console.log(e, "eee");
      this.info.longitude = e.point.lng;
      this.info.latitude = e.point.lat;
      this.infoWindowShow = true;
    },
    getBaiduMapPoint() {
      let that = this;
      let myGeo = new this.BMap.Geocoder();

      myGeo.getPoint(this.searchJingwei, function(point) {
        if (point) {
          that.map.centerAndZoom(point, 15);
          that.info.latitude = point.lat;
          that.info.longitude = point.lng;
          that.infoWindowShow = true;
        }
      });
    },
    //重新选择地图定位，覆盖到input表单里面
    getBaiduMapPointToInput() {
      let that = this;
      let myGeo = new this.BMap.Geocoder();
      that.temp.station_mapx = that.info.latitude;
      that.temp.station_mapy = that.info.longitude;
    },
    //信息窗口关闭
    infoWindowClose() {
      this.latitude = "";
      this.longitude = "";
      this.infoWindowShow = false;
    },

    getList() {
      this.listLoading = true;
      List(this.listQuery).then(response => {
        var data = response.data;
        this.list = data.data;
        this.pagination = data;
        //图片相对路径处理
        //this.list.forEach(item=>{
        //  item.image_path=process.env.VUE_APP_BASE_PIC +  item.image_path

        //})

        //图片放大处理，声明一个数组，遍历一遍
        // this.list.forEach(e => {
        //   e.imglist=[]
        //   e.imglist.push(e.image_path)
        // });
      });

      this.listLoading = false;
    },

    change(val) {
      // this.listQuery.category_idC = null

      //this.$set(this.listQuery, 'category_idC', null)

      List({ category_id: val }).then(response => {
        var data = response.data;
        this.list = data.data;
        this.pagination = data;
      });
    },

    getCtList() {
      Ct_AllList().then(response => {
        var data = response.data;
        this.categoryArr = data;
        //console.log(data);
      });
    },
    handleFilter() {
      //console.log(this.listQuery)
      this.listQuery.page = 1;
      this.getList();
    },

    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    changeStatus(row, status) {
      Status({ id: row.id, status: status }).then(response => {
        row.status = status;
        this.$message.success("操作成功！");
        this.getList();
      });
    },

    orderHandle(row) {
      row.show = 1;
    },

    orderHandleDo(row) {
      Sort({ id: row.id, sort: row.sort }).then(response => {
        row.show = 0;
        this.getList();
        this.$message.success("操作成功！");
      });
    },

    showCreate() {
      this.temp = {
        category_id: null,
        title: "",
        link_url: "",
        image_path: "",
        sort: 0
      };
      this.dialogTitle = "添加";
      this.dialogStatus = "create";
      (this.dialogTitle = "添加"), (this.dialogFormVisible = true);
    },

    handleEdit(row, status) {
      this.dialogTitle = "编辑";
      this.dialogFormVisible = true;
      this.temp = JSON.parse(JSON.stringify(row));
      this.dialogStatus = status;
    },
    updateAction(row) {
      let that = this;
      Info({ id: row.id }).then(res => {
        if (res.code === 0) {
          //this.btn = false
          this.temp = res.data;
          this.dialogFormVisible = true;
          this.dialogTitle = "编辑";
          this.dialogStatus = status;

          // this.infoWindowShow = true

          // this.info.longitude = res.data.station_mapx
          // this.info.latitude = res.data.station_mapy

          that.$nextTick(() => {
            // 选择一个经纬度作为中心点
            // var map = new that.BMap.Map("map");
            // var point = new that.BMap.Point(res.data.station_mapx, res.data.station_mapy)
            // // this.point = new BMap.Point(parseFloat(res.data.station_mapx), parseFloat(res.data.station_mapy));
            // map.centerAndZoom(point, 12);
            // this.$forceUpdate()
            // setTimeout(() => {
            //   window.map.centerAndZoom(new BMap.Point(res.data.station_mapx, res.data.station_mapy), 15); // 初始化地图,设置中心点坐标和地图级
            // }, 300);
          });
          this.info.longitude = res.data.station_mapy;
          this.info.latitude = res.data.station_mapx;
          this.infoWindowShow = true;
          // this.$forceUpdate()

          // this.BMap = BMap
          // this.map = map
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    handleDel(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //console.log(row.id);
          Del({ id: row.id }).then(response => {
            if (response.code === 0) {
              this.$message({
                message: response.msg,
                type: "success"
              });
              this.dialogFormVisible = false;
              this.getList();
            } else {
              this.$message({
                message: response.msg,
                type: "error"
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    handleImageSuccess(res, file) {
      if (res.code === 0) {
        this.temp.image_path = res.data.filepath;
        //图片相对路径处理
        //this.temp.image_path=process.env.VUE_APP_BASE_PIC +  this.temp.image_path
        this.temp.image_path = this.temp.image_path;
        // uploadPath = uploadPath.this.temp.image_path;

        this.$message.success("上传成功！");
      } else {
        this.$message.error(res.msg);
      }
    },
    update() {
      Save(this.temp).then(response => {
        if (response.code === 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          //this.fetchSetting()
          this.getList();
        } else {
          this.$message({
            message: response.msg,
            type: "error"
          });
        }
      });
    },
    create() {
      Save(this.temp).then(response => {
        if (response.code === 0) {
          this.$message({
            message: response.msg,
            type: "success"
          });
          this.dialogFormVisible = false;
          //this.fetchSetting()
          this.getList();
        } else {
          this.$message({
            message: response.msg,
            type: "error"
          });
        }
      });
    }
  }
};
</script>

<style>
#allmap {
  height: 450px;
  width: 100%;
  margin: 10px 0;
}
/* .table-container {
  margin: 10px 0;
} */
.alert-container {
  margin: 20px 0;
}
.bm-view {
  width: 100%;
  height: 300px;
}
#allmap {
  height: 450px;
  width: 100%;
  margin: 10px 0;
}
.widthpick {
  width: 50%;
}
</style>
